<template>
  <div>
    <!-- 搜索栏 -->
    <a-card style="margin-bottom: 16px;">
      <a-form layout="inline">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="客户姓名/手机号"
            style="width: 200px;"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <SearchOutlined />
              查询
            </a-button>
            <a-button @click="handleReset">
              <RedoOutlined />
              重置
            </a-button>
            <a-button type="primary" @click="handleAdd">
              <PlusOutlined />
              新增
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 表格 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleView(record)">
                详情
              </a-button>
              <a-popconfirm
                title="确定删除该客户吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" danger size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      width="600px"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="客户姓名" required>
          <a-input v-model:value="formData.name" placeholder="请输入客户姓名" />
        </a-form-item>
        <a-form-item label="手机号" required>
          <a-input v-model:value="formData.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="身份证号">
          <a-input v-model:value="formData.idCard" placeholder="请输入身份证号" />
        </a-form-item>
        <a-form-item label="地址">
          <a-textarea v-model:value="formData.address" placeholder="请输入地址" :rows="2" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 客户详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="客户详情"
      :footer="null"
      width="1000px"
    >
      <a-spin :spinning="detailLoading">
        <div v-if="customerDetail">
          <!-- 基本信息 -->
          <a-card title="基本信息" style="margin-bottom: 16px;" size="small">
            <a-row :gutter="16">
              <a-col :span="8">
                <div class="detail-item">
                  <span class="detail-label">客户姓名：</span>
                  <span class="detail-value">{{ customerDetail.customer?.name }}</span>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="detail-item">
                  <span class="detail-label">手机号：</span>
                  <span class="detail-value">{{ customerDetail.customer?.phone }}</span>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="detail-item">
                  <span class="detail-label">身份证号：</span>
                  <span class="detail-value">{{ customerDetail.customer?.idCard || '-' }}</span>
                </div>
              </a-col>
            </a-row>
            <a-row :gutter="16" style="margin-top: 16px;">
              <a-col :span="24">
                <div class="detail-item">
                  <span class="detail-label">地址：</span>
                  <span class="detail-value">{{ customerDetail.customer?.address || '-' }}</span>
                </div>
              </a-col>
            </a-row>
            <a-row :gutter="16" style="margin-top: 16px;">
              <a-col :span="24">
                <div class="detail-item">
                  <span class="detail-label">备注：</span>
                  <span class="detail-value">{{ customerDetail.customer?.remark || '-' }}</span>
                </div>
              </a-col>
            </a-row>
          </a-card>

          <!-- 统计信息 -->
          <a-row :gutter="16" style="margin-bottom: 16px;">
            <a-col :span="8">
              <a-card size="small">
                <a-statistic
                  title="名下车辆"
                  :value="customerDetail.vehicleCount"
                  suffix="辆"
                  :value-style="{ color: '#1890ff' }"
                >
                  <template #prefix>
                    <CarOutlined />
                  </template>
                </a-statistic>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card size="small">
                <a-statistic
                  title="保养记录"
                  :value="customerDetail.maintenanceCount"
                  suffix="次"
                  :value-style="{ color: '#faad14' }"
                >
                  <template #prefix>
                    <ToolOutlined />
                  </template>
                </a-statistic>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card size="small">
                <a-statistic
                  title="维修记录"
                  :value="customerDetail.repairCount"
                  suffix="次"
                  :value-style="{ color: '#f5222d' }"
                >
                  <template #prefix>
                    <SettingOutlined />
                  </template>
                </a-statistic>
              </a-card>
            </a-col>
          </a-row>

          <!-- 名下车辆 -->
          <a-card title="名下车辆" style="margin-bottom: 16px;" size="small">
            <a-table
              :columns="vehicleColumns"
              :data-source="customerDetail.vehicles"
              :pagination="false"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'plateNumber'">
                  <a-tag color="blue">{{ record.plateNumber }}</a-tag>
                </template>
              </template>
            </a-table>
          </a-card>

          <!-- 保养记录 -->
          <a-card title="保养记录（最近10条）" style="margin-bottom: 16px;" size="small">
            <a-table
              :columns="maintenanceColumns"
              :data-source="customerDetail.maintenanceRecords"
              :pagination="false"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'cost'">
                  <span style="color: #faad14; font-weight: bold;">¥{{ record.cost }}</span>
                </template>
              </template>
            </a-table>
          </a-card>

          <!-- 维修记录 -->
          <a-card title="维修记录（最近10条）" size="small">
            <a-table
              :columns="repairColumns"
              :data-source="customerDetail.repairRecords"
              :pagination="false"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag v-if="record.status === 'pending'" color="orange">待维修</a-tag>
                  <a-tag v-else-if="record.status === 'repairing'" color="blue">维修中</a-tag>
                  <a-tag v-else-if="record.status === 'completed'" color="green">已完成</a-tag>
                </template>
                <template v-if="column.key === 'cost'">
                  <span style="color: #f5222d; font-weight: bold;">¥{{ record.cost }}</span>
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  getCustomerPage,
  getCustomerDetail,
  addCustomer,
  updateCustomer,
  deleteCustomer
} from '@/api/customer'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  CarOutlined,
  ToolOutlined,
  SettingOutlined
} from '@ant-design/icons-vue'

const loading = ref(false)
const tableData = ref([])
const searchForm = reactive({
  keyword: ''
})

// 详情弹窗
const detailVisible = ref(false)
const detailLoading = ref(false)
const customerDetail = ref(null)

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `共 ${total} 条`
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '客户姓名', dataIndex: 'name', key: 'name' },
  { title: '手机号', dataIndex: 'phone', key: 'phone' },
  { title: '身份证号', dataIndex: 'idCard', key: 'idCard' },
  { title: '地址', dataIndex: 'address', key: 'address', ellipsis: true },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' }
]

// 详情弹窗-车辆表格列
const vehicleColumns = [
  { title: '车牌号', dataIndex: 'plateNumber', key: 'plateNumber', width: 120 },
  { title: '品牌', dataIndex: 'brand', key: 'brand' },
  { title: '车型', dataIndex: 'model', key: 'model' },
  { title: '颜色', dataIndex: 'color', key: 'color', width: 80 },
  { title: '里程(km)', dataIndex: 'mileage', key: 'mileage', width: 100 }
]

// 详情弹窗-保养记录列
const maintenanceColumns = [
  { title: '保养日期', dataIndex: 'maintenanceDate', key: 'maintenanceDate', width: 160 },
  { title: '保养类型', dataIndex: 'maintenanceType', key: 'maintenanceType', width: 100 },
  { title: '保养项目', dataIndex: 'maintenanceItems', key: 'maintenanceItems', ellipsis: true },
  { title: '费用', dataIndex: 'cost', key: 'cost', width: 100 },
  { title: '经办人', dataIndex: 'operator', key: 'operator', width: 80 }
]

// 详情弹窗-维修记录列
const repairColumns = [
  { title: '开始时间', dataIndex: 'startTime', key: 'startTime', width: 160 },
  { title: '故障描述', dataIndex: 'faultDescription', key: 'faultDescription', ellipsis: true },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '费用', dataIndex: 'cost', key: 'cost', width: 100 },
  { title: '维修人员', dataIndex: 'operator', key: 'operator', width: 90 }
]

const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增客户')
const isEdit = ref(false)
const formData = reactive({
  id: null,
  name: '',
  phone: '',
  idCard: '',
  address: '',
  remark: ''
})

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const res = await getCustomerPage({
      current: pagination.current,
      size: pagination.pageSize,
      keyword: searchForm.keyword
    })
    tableData.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  pagination.current = 1
  loadTableData()
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadTableData()
}

// 新增
const handleAdd = () => {
  modalTitle.value = '新增客户'
  isEdit.value = false
  Object.assign(formData, {
    id: null,
    name: '',
    phone: '',
    idCard: '',
    address: '',
    remark: ''
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (record) => {
  modalTitle.value = '编辑客户'
  isEdit.value = true
  Object.assign(formData, record)
  modalVisible.value = true
}

// 查看详情
const handleView = async (record) => {
  detailVisible.value = true
  detailLoading.value = true
  try {
    const res = await getCustomerDetail(record.id)
    customerDetail.value = res.data
  } catch (error) {
    console.error('加载客户详情失败：', error)
  } finally {
    detailLoading.value = false
  }
}

// 删除
const handleDelete = async (id) => {
  try {
    await deleteCustomer(id)
    message.success('删除成功')
    loadTableData()
  } catch (error) {
    console.error('删除失败：', error)
  }
}

// 弹窗确认
const handleModalOk = async () => {
  if (!formData.name || !formData.phone) {
    message.warning('请填写必填项')
    return
  }
  
  modalLoading.value = true
  try {
    if (isEdit.value) {
      await updateCustomer(formData)
      message.success('更新成功')
    } else {
      await addCustomer(formData)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('操作失败：', error)
  } finally {
    modalLoading.value = false
  }
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.detail-item {
  line-height: 32px;
}

.detail-label {
  color: #666;
  font-weight: 500;
}

.detail-value {
  color: #262626;
  margin-left: 4px;
}

:deep(.ant-card-head) {
  background: #fafafa;
  font-weight: 600;
}
</style>

